<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\Request;
use app\admin\service\ExpandCustomer as ExpandCustomerService;
use app\admin\service\Crontab as CrontabService;
use app\admin\service\Serialnumber as SerialnumberService;
use think\facade\Db;

class Crontab extends Base
{
    /**
     * @describe 定时任务，修改ExpandCustomer的Customer_id 字段
     * @author: Bobo
     * @date: 2024-10-28 17:25:03
     * @param [type] @required
     * @return Renderable
     */
    public function syncCustomerId(Request $request, ExpandCustomerService $expandCustomerService)
    {
        $limit = $request->param('limit') ?? 20;
        $result = $expandCustomerService->synCustomerId((int)$limit);
        $code = $result['code'];
        $data = $result['data'] ?? [];
        $message = $result['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    public function generationSMCopywriting(Request $request, CrontabService $service)
    {
        $limit = $request->param('limit') ?? 5;
        $arrData = $service->generationSMCopywriting($limit);
        return json($arrData);
    }

    public function getProfitForCache(CrontabService $service)
    {
        $arrData = $service->getProfitForCache();
        return json($arrData);
    }


    /**
     * @describe 
     * @author: Bobo
     * @date: 2025-06-11 10:22:23 
     * @param [type] @required
     * @return Renderable
     */
    public function generateSnPictures(Request $request, SerialnumberService $service)
    {
        $limit = $request->param('limit') ?? 20;

        $res = Db::name('serialnumber')->where('photo', null)->where('status', '>', -1)->limit((int)$limit)->select();

        $count = 0;
        $start_time = time();

        foreach ($res as $item) {
            $res = $service->generateSnPictures(['sn_id' => $item['sn_id']]);

            if ($res['code'] == 0) {
                $count++;
            }
        }
        $end_time = time();
        $time = $end_time - $start_time;

        return $this->returnJsonData(0, ['count' => $count, 'time' => $time], 'success');
    }
}
